package cn.gzjp.modules.logis.web;

import cn.gzjp.common.constant.LogisUserType;
import cn.gzjp.common.mapper.JsonMapper;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.utils.DateUtils;
import cn.gzjp.common.utils.MyBeanUtils;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.common.utils.excel.ExportExcel;
import cn.gzjp.common.utils.excel.ImportExcel;
import cn.gzjp.common.web.AjaxResult;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.modules.logis.entity.LogisCar;
import cn.gzjp.modules.logis.entity.LogisUser;
import cn.gzjp.modules.logis.service.LogisCarService;
import cn.gzjp.modules.logis.service.LogisUserService;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * 司机认证Controller
 * @author zengcp
 * @version 2018-04-03
 */
@Controller
@RequestMapping(value = "${adminPath}/logis/logisDriver")
public class LogisDriverController extends BaseController {

	@Autowired
	private LogisCarService logisCarService;
	@Autowired
	private LogisUserService logisUserService;
	
	
	/**
	 * 司机认证列表页面
	 */
	@RequiresPermissions("logis:logisCar:list")
	@RequestMapping(value = {"list", ""})
	public String list(LogisCar logisCar, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<LogisCar> page = logisCarService.findPage(new Page<LogisCar>(request, response), logisCar); 
		model.addAttribute("page", page);
		return "modules/logis/logisDriverList";
	}

	/**
	 * 查看，增加，编辑司机认证表单页面
	 */
	@RequiresPermissions(value={"logis:logisCar:view","logis:logisCar:add","logis:logisCar:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(LogisCar logisCar, Model model) {
		model.addAttribute("logisCar", logisCar);
		return "modules/logis/logisDriverForm";
	}


	/**
	 * 保存司机认证
	 */
	@RequiresPermissions(value={"logis:logisCar:add","logis:logisCar:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(LogisCar logisCar, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, logisCar)){
			return form(logisCar, model);
		}
		if(!logisCar.getIsNewRecord()){//编辑表单保存
			LogisCar t = logisCarService.get(logisCar.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(logisCar, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			logisCarService.save(t);//保存
			LogisUser user = logisUserService.get(t.getId());
			user.setLicensePlate(t.getLicensePlate());
			logisUserService.save(user);
		}else{//新增表单保存
			logisCarService.save(logisCar);//保存
		}
		addMessage(redirectAttributes, "保存司机认证成功");
		return redirect("/logis/logisDriver/?repage");
	}
	
	/**
	 * 删除司机认证
	 */
	@RequiresPermissions("logis:logisCar:del")
	@RequestMapping(value = "delete")
	public String delete(LogisCar logisCar, RedirectAttributes redirectAttributes) {
		logisCarService.delete(logisCar);
		addMessage(redirectAttributes, "删除司机认证成功");
		return redirect("/logis/logisDriver/?repage");
	}
	
	/**
	 * 批量删除司机认证
	 */
	@RequiresPermissions("logis:logisCar:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			logisCarService.delete(logisCarService.get(id));
		}
		addMessage(redirectAttributes, "删除司机认证成功");
		return redirect("/logis/logisDriver/?repage");
	}
	/**
	 * 审核
	 */
	@RequestMapping(value = "confirm", method=RequestMethod.POST)
	@ResponseBody
	public String confirm(String id,String mobile,String realName,String gender,String birthDay,
							String zjcx,String cclzrq,String yxqqssj,String yxqzssj,String licensePlate,String address) {
		AjaxResult result = new AjaxResult(true,"操作成功");
		LogisCar logisCar = logisCarService.get(id);
		logisCar.setMobile(mobile);
		logisCar.setRealName(realName);
		logisCar.setGender(gender);
		logisCar.setBirthDay(birthDay);
		logisCar.setZjcx(zjcx);
		logisCar.setCclzrq(cclzrq);
		logisCar.setYxqqssj(yxqqssj);
		logisCar.setYxqzssj(yxqzssj);
		logisCar.setLicensePlate(licensePlate);
        logisCar.setAddress(address);
		logisCarService.save(logisCar);
		if(StrUtil.isNotBlank(logisCar.getRealName())){
			LogisUser user = logisUserService.get(logisCar.getId());
			user.setRealName(logisCar.getRealName());
			logisUserService.save(user);
		}
		return JsonMapper.getInstance().toJson(result);
	}



	/**
	 * 审核通过
	 */
	@RequestMapping(value = "auditPass", method=RequestMethod.GET)
	public String auditPass(String id,RedirectAttributes redirectAttributes) {
		LogisCar logisCar = logisCarService.get(id);
		if(StrUtil.isBlank(logisCar.getRealName())){
			addMessage(redirectAttributes, "请先设置司机真实姓名，审核通过失败！");
			return redirect("/logis/logisDriver/?repage");
		}
		logisCar.setDriverStatus(1);
		logisCar.setDriverRefusalReason("");
		logisCarService.save(logisCar);
		LogisUser user = logisUserService.get(logisCar.getId());
		user.setType(LogisUserType.DRIVER);
		logisUserService.save(user);
		addMessage(redirectAttributes, "审核通过操作成功");
		return redirect("/logis/logisDriver/?repage");
	}
	/**
	 * 审核拒绝
	 */
	@RequestMapping(value = "auditRefuse", method=RequestMethod.GET)
	public String auditRefuse(String id,String driverRefusalReason,RedirectAttributes redirectAttributes) {
		LogisCar logisCar = logisCarService.get(id);
		logisCar.setDriverStatus(2);
		logisCar.setDriverRefusalReason(driverRefusalReason);
		logisCarService.save(logisCar);
		addMessage(redirectAttributes, "审核拒绝操作成功");
		return redirect("/logis/logisDriver/?repage");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("logis:logisCar:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(LogisCar logisCar, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "司机认证"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<LogisCar> page = logisCarService.findPage(new Page<LogisCar>(request, response, -1), logisCar);
    		new ExportExcel("司机认证", LogisCar.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出司机认证记录失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisDriver/?repage");
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("logis:logisCar:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<LogisCar> list = ei.getDataList(LogisCar.class);
			for (LogisCar logisCar : list){
				try{
					logisCarService.save(logisCar);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条司机认证记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条司机认证记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入司机认证失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisDriver/?repage");
    }
	
	/**
	 * 下载导入司机认证数据模板
	 */
	@RequiresPermissions("logis:logisCar:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "司机认证数据导入模板.xlsx";
    		List<LogisCar> list = Lists.newArrayList(); 
    		new ExportExcel("司机认证数据", LogisCar.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisDriver/?repage");
    }
	@ModelAttribute
	public LogisCar get(@RequestParam(required=false) String id) {
		LogisCar entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = logisCarService.get(id);
		}
		if (entity == null){
			entity = new LogisCar();
		}
		return entity;
	}
	

}